/**
 * Created by AllanXu on 01/18/2016.
 */
define(function (require) {
    var Vue = require('vue'),
        Config = require('config'),
        _ = require('ajax'),
        utilities = require('utilities'),
        imageTool = require('imageTool');

    var addCode = sessionStorage.getItem("addCode") ? sessionStorage.getItem("addCode") : "36";

    // 认证
    var AuthDialog = require('auth_dialog');
    var authDialog = new AuthDialog();
    // 禁用申诉
    var Forbidden = require('forbidden');
    var forbidden = new Forbidden();

    var app = new Vue({
        el: '#publish',
        data: {
            leaveWords: '',
            publicContent: '',
            url1: '',
            url2: '',
            url3: '',
            url4: '',
            url5: '',
            url6: '',
            url7: '',
            url8: '',
            url9: '',
            picServer: Config.picServer,
            defaultAdd: '江西省',
            msgid: '',
            userInfo: ''
        },
        methods: {
            init: function () {
                // 右上角地区
                var addName = sessionStorage.getItem('addName');
                app.defaultAdd = addName || app.defaultAdd;
            },
            sendPublic: function () {
                _(Config.SERVICE.INDEX.MOODPUBLIC, {
                    "id": sessionStorage.id,
                    'dynamic.content': app.publicContent,
                    'dynamic.url1': app.url1,
                    'dynamic.url2': app.url2,
                    'dynamic.url3': app.url3,
                    'dynamic.url4': app.url4,
                    'dynamic.url5': app.url5,
                    'dynamic.url6': app.url6,
                    'dynamic.url7': app.url7,
                    'dynamic.url8': app.url8,
                    'dynamic.url9': app.url9
                }, function (data) {
                    console.log(data);
                    if (data.code == 200) {
                        alert("发布成功~")
                        app.init();
                        app.publicContent = '';
                        app.showPublic = false;
                        window.history.back();
                    }
                });
            },
            removediv: function (num) {
                console.log(1);
                if (num == 1)
                    app.url1 = '';
                else if (num == 2)
                    app.url2 = '';
                else if (num == 3)
                    app.url3 = '';
                else if (num == 4)
                    app.url4 = '';
                else if (num == 5)
                    app.url5 = '';
                else if (num == 6)
                    app.url6 = '';
                else if (num == 7)
                    app.url7 = '';
                else if (num == 8)
                    app.url8 = '';
                else if (num == 9)
                    app.url9 = '';
            },
            fileChanged: function (e) {

                if (e.currentTarget.files.length === 0)
                    return;

                var file = e.currentTarget.files[0];
                var formData = new FormData();
                imageTool.resize(file, {
                    width: 800, // maximum width
                    height: 800 // maximum height
                }, function (blob, didItResize) {
                    // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
                    // document.getElementById('preview').src = window.URL.createObjectURL(blob);
                    // you can also now upload this blob using an XHR.

                    // document.getElementById('test').src = window.URL.createObjectURL(blob);

                    blobToDataURL(blob, function (res) {
                        formData.append('imgStr', res);

                        var xmlhttp = new XMLHttpRequest();
                        xmlhttp.onreadystatechange = function () {
                            if (xmlhttp.readyState == 4) {
                                try {
                                    var response = JSON.parse(xmlhttp.responseText);
                                    if (app.url1 == '') {
                                        app.url1 = response.url;
                                        //$('.right').after('<div class="img-item" id="url1"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(1)"></i></div>');
                                    } else if (app.url2 == '') {
                                        app.url2 = response.url;
                                        //$('.right').after('<div class="img-item" id="url2"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(2)"></i></div>');
                                    } else if (app.url3 == '') {
                                        app.url3 = response.url;
                                        //$('.right').after('<div class="img-item" id="url3"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(3)"></i></div>');
                                    } else if (app.url4 == '') {
                                        app.url4 = response.url;
                                        //$('.right').after('<div class="img-item" id="url4"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(4)"></i></div>');
                                    } else if (app.url5 == '') {
                                        app.url5 = response.url;
                                        //$('.right').after('<div class="img-item" id="url5"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(5)"></i></div>');
                                    } else if (app.url6 == '') {
                                        app.url6 = response.url;
                                        //$('.right').after('<div class="img-item" id="url6"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(6)"></i></div>');
                                    } else if (app.url7 == '') {
                                        app.url7 = response.url;
                                        //$('.right').after('<div class="img-item" id="url7"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(7)"></i></div>');
                                    } else if (app.url8 == '') {
                                        app.url8 = response.url;
                                        //$('.right').after('<div class="img-item" id="url8"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(8)"></i></div>');
                                    } else if (app.url9 == '') {
                                        app.url9 = response.url;
                                        //$('.right').after('<div class="img-item" id="url9"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(9)"></i></div>');
                                    } else {
                                        alert("最多只能上传9张照片！");
                                    }
                                    document.querySelector('#pic').value = '';
                                } catch (e) {
                                    console.log(e);
                                    alert('上传失败！');
                                }
                            }
                        };
                        xmlhttp.open('POST', Config.SERVICE.USERCENTER.IMGUPLOADDO);
                        xmlhttp.send(formData);
                    });

                });
            }
        }
    });
    app.init();

    function dataURItoBlob (dataURI) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
        var byteString = atob(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to an ArrayBuffer
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        //Old Code
        //write the ArrayBuffer to a blob, and you're done
        //var bb = new BlobBuilder();
        //bb.append(ab);
        //return bb.getBlob(mimeString);

        //New Code
        return new Blob([ab], {type: mimeString});


    }

    function blobToDataURL (blob, callback) {
        var a = new FileReader();
        a.onload = function (e) {
            callback(e.target.result);
        }
        a.readAsDataURL(blob);
    }

    /* $("#pic").change(function(){
     var maxSize = 200 * 1024;   //200KB
     var file = this.files[0],   //读取文件
     reader = new FileReader();
     reader.onload = function() {
     var result = this.result,   //result为data url的形式
     img = new Image();
     img.src = result;
     console.log(result.length);
     if(result.length < maxSize) {
     // console.log(result);      //图片直接上传
     $.ajax({
     url: Config.SERVICE.USERCENTER.IMGUPLOAD,
     type: "POST",
     data: {
     "imgFile": result
     },
     success: function(data) {
     console.log(data);
     // $(".showPic").show().attr('data-url',"/"+ data.url);
     }
     });
     } else {
     var data = compress(img);    //图片首先进行压缩
     //console.log(data);                //图片上传

     }
     }
     reader.readAsDataURL(file);
     });

     var canvas = document.createElement('canvas'),
     ctx = canvas.getContext('2d');
     function compress(img) {
     canvas.width = img.width;
     canvas.height = img.height;
     //利用canvas进行绘图
     //将原来图片的质量压缩到原先的0.2倍。
     var data = canvas.toDataURL('image/jpeg', 0.2); //data url的形式
     //console.log(canvas.toDataURL("image/jpeg", 0.2).split(',')[1]);
     $.ajax({
     url: Config.SERVICE.USERCENTER.IMGUPLOADDO,
     type: "GET",
     data: {
     "imgFile": canvas.toDataURL("image/jpeg", 0.2)
     },
     success: function(data) {
     console.log(data);
     // $(".showPic").show().attr('data-url',"/"+ data.url);
     }
     });

     return data;
     }*/

    //图片上传
    /*$('#pic').AjaxFileUpload({
     action: Config.SERVICE.USERCENTER.IMGUPLOAD,
     onComplete: function (filename, response) {
     //console.log(response.title);
     //console.log(response.url);
     if(app.url1==''){
     app.url1=response.url;
     //$('.right').after('<div class="img-item" id="url1"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(1)"></i></div>');
     }else if(app.url2==''){
     app.url2=response.url;
     //$('.right').after('<div class="img-item" id="url2"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(2)"></i></div>');
     }else if(app.url3==''){
     app.url3=response.url;
     //$('.right').after('<div class="img-item" id="url3"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(3)"></i></div>');
     }else if(app.url4==''){
     app.url4=response.url;
     //$('.right').after('<div class="img-item" id="url4"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(4)"></i></div>');
     }else if(app.url5==''){
     app.url5=response.url;
     //$('.right').after('<div class="img-item" id="url5"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(5)"></i></div>');
     }else if(app.url6==''){
     app.url6=response.url;
     //$('.right').after('<div class="img-item" id="url6"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(6)"></i></div>');
     }else if(app.url7==''){
     app.url7=response.url;
     //$('.right').after('<div class="img-item" id="url7"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(7)"></i></div>');
     }else if(app.url8==''){
     app.url8=response.url;
     //$('.right').after('<div class="img-item" id="url8"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(8)"></i></div>');
     }else if(app.url9==''){
     app.url9=response.url;
     //$('.right').after('<div class="img-item" id="url9"><img src="'+Config.picServer+response.url+'" alt=""><i class="iconfont icon-x" onclick="removediv(9)"></i></div>');
     }else{
     alert("最多只能上传9张照片！");
     }
     }
     });*/
});